package cn.liontalk.exception;

import cn.liontalk.common.result.CodeMsg;
import cn.liontalk.common.result.Result;
import cn.liontalk.controller.LoginController;
import org.apache.ibatis.binding.BindingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author: 周哲
 * @package: cn.liontalk.service
 * @description:
 * @date: 2019/1/19 16:06
 * @version: V1.0
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private static Logger log = LoggerFactory.getLogger(LoginController.class);


    @ExceptionHandler(value = Exception.class)
    public Result <String> exceptionHandler(Exception e) {
        e.printStackTrace();
        if (e instanceof GlobalException) {
            GlobalException globalException = (GlobalException) e;
            return Result.error(globalException.getCodeMsg());
        }
        if (e instanceof BindException) {
            BindException bindingException = (BindException) e;
            List <ObjectError> list = bindingException.getAllErrors();
            ObjectError objectError = list.get(0);
            String message = objectError.getDefaultMessage();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(message));
        } else {
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }


}
